package etnorservice.etnor_service.service.project;

import etnorservice.etnor_service.domain.*;
import etnorservice.etnor_service.domain.dto.*;
import etnorservice.etnor_service.exception.BusinessException;
import etnorservice.etnor_service.mapper.*;
import etnorservice.etnor_service.mapper.projectMapper.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ProjectService {

    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private ProjectScreenshotMapper screenshotMapper;

    @Autowired
    private ProjectTagMapper tagMapper;

    @Autowired
    private ProjectCategoryMapper categoryMapper;

    @Autowired
    private ProjectCategoryMappingMapper categoryMappingMapper;

    @Autowired
    private ProjectFeatureMapper featureMapper;

    @Autowired
    private ProjectRequirementMapper requirementMapper;

    @Autowired
    private DownloadTokenMapper downloadTokenMapper;

    @Autowired
    private DownloadRecordMapper downloadRecordMapper;

    @Value("${gitee.owner}")
    private String giteeOwner;

    @Value("${gitee.access-token}")
    private String giteeAccessToken;

    @Value("${gitee.repo-prefix:project-}")
    private String giteeRepoPrefix;

    private final RestTemplate restTemplate = new RestTemplate();

    /**
     * 创建Gitee仓库
     */
    public Map<String, String> createGiteeRepository(String projectName, String description) {
        try {
            // 仓库名格式: project-[随机8位字符]
            String repoName = giteeRepoPrefix + UUID.randomUUID().toString().substring(0, 8);

            // 构建请求参数
            Map<String, Object> requestParams = new HashMap<>();
            requestParams.put("access_token", giteeAccessToken);
            requestParams.put("name", repoName);
            requestParams.put("description", description);
            requestParams.put("private", true);  // 创建私有仓库
            requestParams.put("auto_init", true); // 使用README初始化仓库

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestParams, headers);

            // 调用Gitee API创建仓库
            String apiUrl = "https://gitee.com/api/v5/user/repos";
            ResponseEntity<Map> response = restTemplate.postForEntity(apiUrl, requestEntity, Map.class);

            if (response.getStatusCode().is2xxSuccessful()) {
                Map<String, String> result = new HashMap<>();
                result.put("repoName", repoName);
                result.put("webUrl", "https://gitee.com/" + giteeOwner + "/" + repoName);
                result.put("cloneUrl", "https://gitee.com/" + giteeOwner + "/" + repoName + ".git");
                result.put("downloadUrl", "https://gitee.com/" + giteeOwner + "/" + repoName + "/repository/archive/master.zip");

                return result;
            } else {
                throw new BusinessException("创建Gitee仓库失败: " + response.getBody());
            }
        } catch (Exception e) {
            throw new BusinessException("创建Gitee仓库异常: " + e.getMessage());
        }
    }

    /**
     * 创建新项目 (支持Gitee集成)
     */
    @Transactional
    public ProjectDTO createProject(ProjectDTO projectDTO) {
        // 转换DTO为实体
        Project project = new Project();
        BeanUtils.copyProperties(projectDTO, project);

        // 设置初始状态
        project.setStatus("draft");
        project.setDownloadCount(0);
        project.setViewCount(0);

        // 如果有Gitee仓库信息，保存到项目中
        if (projectDTO.getGiteeRepoName() != null && projectDTO.getGiteeRepoUrl() != null) {
            project.setGiteeRepoName(projectDTO.getGiteeRepoName());
            project.setGiteeRepoUrl(projectDTO.getGiteeRepoUrl());
            project.setGiteeDownloadUrl(projectDTO.getGiteeDownloadUrl());

            // 如果使用Gitee托管，将下载URL设置为文件路径
            if (projectDTO.getGiteeDownloadUrl() != null && !projectDTO.getGiteeDownloadUrl().isEmpty()) {
                project.setFilePath(projectDTO.getGiteeDownloadUrl());
            }
        }
        project.setCoverImage(projectDTO.getScreenshots().get(0).getPath());
        // 保存项目基本信息
        projectMapper.insert(project);
        Long projectId = project.getId();

        // 保存项目分类关联
//        if (projectDTO.getCategories() != null && !projectDTO.getCategories().isEmpty()) {
//            List<ProjectCategory> categories = categoryMapper.findAll();
//            Map<String, Long> categoryNameToIdMap = categories.stream()
//                    .collect(Collectors.toMap(ProjectCategory::getName, ProjectCategory::getId));
//
//            for (String categoryName : projectDTO.getCategories()) {
//                Long categoryId = categoryNameToIdMap.get(categoryName);
//                if (categoryId != null) {
//                    ProjectCategoryMapping mapping = new ProjectCategoryMapping();
//                    mapping.setProjectId(projectId);
//                    mapping.setCategoryId(categoryId);
//                    categoryMappingMapper.insert(mapping);
//                }
//            }
//        }

        // 保存项目标签
        if (projectDTO.getTags() != null && !projectDTO.getTags().isEmpty()) {
            for (String tagName : projectDTO.getTags()) {
                ProjectTag tag = new ProjectTag();
                tag.setProjectId(projectId);
                tag.setTagName(tagName);
                tagMapper.insert(tag);
            }
        }
        System.out.println("项目截图=============>"+projectDTO.getScreenshots());
        // 保存项目截图
        if (projectDTO.getScreenshots() != null && !projectDTO.getScreenshots().isEmpty()) {
            for (int i = 0; i < projectDTO.getScreenshots().size(); i++) {
                ProjectScreenshotDTO screenshotDTO = projectDTO.getScreenshots().get(i);
                ProjectScreenshot screenshot = new ProjectScreenshot();
                screenshot.setProjectId(projectId);
                screenshot.setImagePath(screenshotDTO.getPath());
                screenshot.setDisplayOrder(i);
                screenshotMapper.insert(screenshot);
            }
        }

        // 保存项目功能
        if (projectDTO.getFeatures() != null && !projectDTO.getFeatures().isEmpty()) {
            for (int i = 0; i < projectDTO.getFeatures().size(); i++) {
                ProjectFeatureDTO featureDTO = projectDTO.getFeatures().get(i);
                ProjectFeature feature = new ProjectFeature();
                feature.setProjectId(projectId);
                feature.setFeatureTitle(featureDTO.getFeatureTitle());
                feature.setFeatureDescription(featureDTO.getFeatureDescription());
                feature.setDisplayOrder(i);
                featureMapper.insert(feature);
            }
        }

        // 保存项目要求
        if (projectDTO.getRequirements() != null && !projectDTO.getRequirements().isEmpty()) {
            for (int i = 0; i < projectDTO.getRequirements().size(); i++) {
                ProjectRequirementDTO requirementDTO = projectDTO.getRequirements().get(i);
                ProjectRequirement requirement = new ProjectRequirement();
                requirement.setProjectId(projectId);
                requirement.setRequirementType(requirementDTO.getRequirementType());
                requirement.setMinRequirement(requirementDTO.getMinRequirement());
                requirement.setRecommendedRequirement(requirementDTO.getRecommendedRequirement());
                requirement.setDisplayOrder(i);
                requirementMapper.insert(requirement);
            }
        }

        // 返回完整的项目DTO
        return getProjectById(projectId);
    }

    /**
     * 获取项目详情
     */
    public ProjectDTO getProjectById(Long id) {
        // 获取项目基本信息
        Project project = projectMapper.findById(id);
        if (project == null) {
            throw new BusinessException("项目不存在");
        }

        // 增加浏览次数
        projectMapper.incrementViewCount(id);

        // 转换为DTO
        ProjectDTO projectDTO = new ProjectDTO();
        BeanUtils.copyProperties(project, projectDTO);

        // 复制Gitee相关字段
        projectDTO.setGiteeRepoName(project.getGiteeRepoName());
        projectDTO.setGiteeRepoUrl(project.getGiteeRepoUrl());
        projectDTO.setGiteeDownloadUrl(project.getGiteeDownloadUrl());

        // 获取项目分类
        List<ProjectCategoryMapping> categoryMappings = categoryMappingMapper.findByProjectId(id);
        if (!categoryMappings.isEmpty()) {
            List<Long> categoryIds = categoryMappings.stream()
                    .map(ProjectCategoryMapping::getCategoryId)
                    .collect(Collectors.toList());

            List<String> categoryNames = new ArrayList<>();
            for (Long categoryId : categoryIds) {
                ProjectCategory category = categoryMapper.findById(categoryId);
                if (category != null) {
                    categoryNames.add(category.getName());
                }
            }
            projectDTO.setCategories(categoryNames);
        }

        // 获取项目标签
        List<ProjectTag> tags = tagMapper.findByProjectId(id);
        if (!tags.isEmpty()) {
            List<String> tagNames = tags.stream()
                    .map(ProjectTag::getTagName)
                    .collect(Collectors.toList());
            projectDTO.setTags(tagNames);
        }

        // 获取项目截图
        List<ProjectScreenshot> screenshots = screenshotMapper.findByProjectId(id);
        if (!screenshots.isEmpty()) {
            List<ProjectScreenshotDTO> screenshotDTOs = screenshots.stream()
                    .map(screenshot -> {
                        ProjectScreenshotDTO dto = new ProjectScreenshotDTO();
                        BeanUtils.copyProperties(screenshot, dto);
                        return dto;
                    })
                    .collect(Collectors.toList());
            projectDTO.setScreenshots(screenshotDTOs);
        }

        // 获取项目功能
        List<ProjectFeature> features = featureMapper.findByProjectId(id);
        if (!features.isEmpty()) {
            List<ProjectFeatureDTO> featureDTOs = features.stream()
                    .map(feature -> {
                        ProjectFeatureDTO dto = new ProjectFeatureDTO();
                        BeanUtils.copyProperties(feature, dto);
                        return dto;
                    })
                    .collect(Collectors.toList());
            projectDTO.setFeatures(featureDTOs);
        }

        // 获取项目要求
        List<ProjectRequirement> requirements = requirementMapper.findByProjectId(id);
        if (!requirements.isEmpty()) {
            List<ProjectRequirementDTO> requirementDTOs = requirements.stream()
                    .map(requirement -> {
                        ProjectRequirementDTO dto = new ProjectRequirementDTO();
                        BeanUtils.copyProperties(requirement, dto);
                        return dto;
                    })
                    .collect(Collectors.toList());
            projectDTO.setRequirements(requirementDTOs);
        }

        return projectDTO;
    }

    /**
     * 更新项目信息
     */
    @Transactional
    public ProjectDTO updateProject(Long id, ProjectDTO projectDTO) {
        // 检查项目是否存在
        Project existingProject = projectMapper.findById(id);
        if (existingProject == null) {
            throw new BusinessException("项目不存在");
        }

        // 检查是否是项目创建者
        if (!existingProject.getCreatorId().equals(projectDTO.getCreatorId())) {
            throw new BusinessException("无权限修改此项目");
        }

        // 更新项目基本信息
        Project project = new Project();
        BeanUtils.copyProperties(projectDTO, project);
        project.setId(id);

        // 更新Gitee相关信息
        if (projectDTO.getGiteeRepoName() != null && projectDTO.getGiteeRepoUrl() != null) {
            project.setGiteeRepoName(projectDTO.getGiteeRepoName());
            project.setGiteeRepoUrl(projectDTO.getGiteeRepoUrl());
            project.setGiteeDownloadUrl(projectDTO.getGiteeDownloadUrl());

            // 如果使用Gitee托管，将下载URL设置为文件路径
            if (projectDTO.getGiteeDownloadUrl() != null && !projectDTO.getGiteeDownloadUrl().isEmpty()) {
                project.setFilePath(projectDTO.getGiteeDownloadUrl());
            }
        }

        projectMapper.update(project);

        // 更新项目分类关联
        categoryMappingMapper.deleteByProjectId(id);
        if (projectDTO.getCategories() != null && !projectDTO.getCategories().isEmpty()) {
            List<ProjectCategory> categories = categoryMapper.findAll();
            Map<String, Long> categoryNameToIdMap = categories.stream()
                    .collect(Collectors.toMap(ProjectCategory::getName, ProjectCategory::getId));

            for (String categoryName : projectDTO.getCategories()) {
                Long categoryId = categoryNameToIdMap.get(categoryName);
                if (categoryId != null) {
                    ProjectCategoryMapping mapping = new ProjectCategoryMapping();
                    mapping.setProjectId(id);
                    mapping.setCategoryId(categoryId);
                    categoryMappingMapper.insert(mapping);
                }
            }
        }

        // 更新项目标签
        tagMapper.deleteByProjectId(id);
        if (projectDTO.getTags() != null && !projectDTO.getTags().isEmpty()) {
            for (String tagName : projectDTO.getTags()) {
                ProjectTag tag = new ProjectTag();
                tag.setProjectId(id);
                tag.setTagName(tagName);
                tagMapper.insert(tag);
            }
        }

        // 更新项目截图
        screenshotMapper.deleteByProjectId(id);
        if (projectDTO.getScreenshots() != null && !projectDTO.getScreenshots().isEmpty()) {
            for (int i = 0; i < projectDTO.getScreenshots().size(); i++) {
                ProjectScreenshotDTO screenshotDTO = projectDTO.getScreenshots().get(i);
                ProjectScreenshot screenshot = new ProjectScreenshot();
                screenshot.setProjectId(id);
                screenshot.setImagePath(screenshotDTO.getPath());
                screenshot.setDisplayOrder(i);
                screenshotMapper.insert(screenshot);
            }
        }

        // 更新项目功能
        featureMapper.deleteByProjectId(id);
        if (projectDTO.getFeatures() != null && !projectDTO.getFeatures().isEmpty()) {
            for (int i = 0; i < projectDTO.getFeatures().size(); i++) {
                ProjectFeatureDTO featureDTO = projectDTO.getFeatures().get(i);
                ProjectFeature feature = new ProjectFeature();
                feature.setProjectId(id);
                feature.setFeatureTitle(featureDTO.getFeatureTitle());
                feature.setFeatureDescription(featureDTO.getFeatureDescription());
                feature.setDisplayOrder(i);
                featureMapper.insert(feature);
            }
        }

        // 更新项目要求
        requirementMapper.deleteByProjectId(id);
        if (projectDTO.getRequirements() != null && !projectDTO.getRequirements().isEmpty()) {
            for (int i = 0; i < projectDTO.getRequirements().size(); i++) {
                ProjectRequirementDTO requirementDTO = projectDTO.getRequirements().get(i);
                ProjectRequirement requirement = new ProjectRequirement();
                requirement.setProjectId(id);
                requirement.setRequirementType(requirementDTO.getRequirementType());
                requirement.setMinRequirement(requirementDTO.getMinRequirement());
                requirement.setRecommendedRequirement(requirementDTO.getRecommendedRequirement());
                requirement.setDisplayOrder(i);
                requirementMapper.insert(requirement);
            }
        }

        // 返回更新后的项目DTO
        return getProjectById(id);
    }

    /**
     * 删除项目
     */
    @Transactional
    public void deleteProject(Long id, Long creatorId) {
        // 检查项目是否存在
        Project project = projectMapper.findById(id);
        if (project == null) {
            throw new BusinessException("项目不存在");
        }

        // 检查是否是项目创建者
        if (!project.getCreatorId().equals(creatorId)) {
            throw new BusinessException("无权限删除此项目");
        }

        // 如果项目使用了Gitee托管，可以考虑删除Gitee仓库
        // 注意：根据实际需求决定是否删除远程仓库
        if (project.getGiteeRepoName() != null && !project.getGiteeRepoName().isEmpty()) {
            try {
                deleteGiteeRepository(project.getGiteeRepoName());
            } catch (Exception e) {
                // 记录日志但不中断流程
                System.err.println("删除Gitee仓库失败: " + e.getMessage());
            }
        }

        // 软删除项目
        projectMapper.delete(id);
    }

    /**
     * 删除Gitee仓库
     */
    private void deleteGiteeRepository(String repoName) {
        try {
            String apiUrl = "https://gitee.com/api/v5/repos/" + giteeOwner + "/" + repoName
                    + "?access_token=" + giteeAccessToken;

            restTemplate.delete(apiUrl);
        } catch (Exception e) {
            throw new BusinessException("删除Gitee仓库失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户的项目列表
     */
    public List<ProjectDTO> getUserProjects(Long userId) {
        List<Project> projects = projectMapper.findByCreatorId(userId);
        return projects.stream()
                .map(project -> {
                    ProjectDTO dto = new ProjectDTO();
                    BeanUtils.copyProperties(project, dto);

                    // 复制Gitee相关字段
                    dto.setGiteeRepoName(project.getGiteeRepoName());
                    dto.setGiteeRepoUrl(project.getGiteeRepoUrl());
                    dto.setGiteeDownloadUrl(project.getGiteeDownloadUrl());

                    return dto;
                })
                .collect(Collectors.toList());
    }

    /**
     * 获取已发布的项目列表
     */
    public List<ProjectDTO> getPublishedProjects(int page, int size) {
        int offset = (page - 1) * size;
        List<Project> projects = projectMapper.findAllPublished(offset, size);
        return projects.stream()
                .map(project -> {
                    ProjectDTO dto = new ProjectDTO();
                    BeanUtils.copyProperties(project, dto);

                    // 复制Gitee相关字段
                    dto.setGiteeRepoName(project.getGiteeRepoName());
                    dto.setGiteeRepoUrl(project.getGiteeRepoUrl());
                    dto.setGiteeDownloadUrl(project.getGiteeDownloadUrl());

                    return dto;
                })
                .collect(Collectors.toList());
    }

    /**
     * 获取免费/付费项目列表
     */
    public List<ProjectDTO> getProjectsByIsFree(boolean isFree, int page, int size) {
        int offset = (page - 1) * size;
        List<Project> projects = projectMapper.findByIsFree(isFree, offset, size);
        return projects.stream()
                .map(project -> {
                    ProjectDTO dto = new ProjectDTO();
                    BeanUtils.copyProperties(project, dto);

                    // 复制Gitee相关字段
                    dto.setGiteeRepoName(project.getGiteeRepoName());
                    dto.setGiteeRepoUrl(project.getGiteeRepoUrl());
                    dto.setGiteeDownloadUrl(project.getGiteeDownloadUrl());

                    return dto;
                })
                .collect(Collectors.toList());
    }

    /**
     * 发布项目
     */
    public void publishProject(Long id, Long creatorId) {
        // 检查项目是否存在
        Project project = projectMapper.findById(id);
        if (project == null) {
            throw new BusinessException("项目不存在");
        }

        // 检查是否是项目创建者
        if (!project.getCreatorId().equals(creatorId)) {
            throw new BusinessException("无权限操作此项目");
        }

        // 检查项目必要信息是完整的
        if (project.getName() == null || project.getName().isEmpty()) {
            throw new BusinessException("项目名称不能为空");
        }

        if (project.getDescription() == null || project.getDescription().isEmpty()) {
            throw new BusinessException("项目描述不能为空");
        }

        // 检查文件路径，可以是本地路径或Gitee下载路径
        boolean hasFilePath = project.getFilePath() != null && !project.getFilePath().isEmpty();
        boolean hasGiteeDownload = project.getGiteeDownloadUrl() != null && !project.getGiteeDownloadUrl().isEmpty();

        if (!hasFilePath && !hasGiteeDownload) {
            throw new BusinessException("项目文件不能为空");
        }

        // 更新项目状态为已发布
        project.setStatus("published");
        projectMapper.update(project);
    }

    /**
     * 生成项目下载令牌
     */
    public String generateDownloadToken(Long userId, Long projectId, String ipAddress) {
        // 检查项目是否存在
        Project project = projectMapper.findById(projectId);
        if (project == null) {
            throw new BusinessException("项目不存在");
        }

        // 检查项目是否已发布
        if (!"published".equals(project.getStatus())) {
            throw new BusinessException("项目未发布");
        }

        // 生成令牌
        String token = UUID.randomUUID().toString().replace("-", "");

        // 计算过期时间 (1小时后)
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR, 1);
        Date expiresAt = calendar.getTime();

        // 保存令牌
        DownloadToken downloadToken = new DownloadToken();
        downloadToken.setUserId(userId);
        downloadToken.setProjectId(projectId);
        downloadToken.setToken(token);
        downloadToken.setExpiresAt(expiresAt);
        downloadToken.setIpAddress(ipAddress);
        downloadToken.setIsUsed(false);

        downloadTokenMapper.insert(downloadToken);

        return token;
    }

    /**
     * 验证下载令牌并处理下载
     */
    @Transactional
    public String validateDownloadToken(String token, String ipAddress) {
        // 验证令牌
        DownloadToken downloadToken = downloadTokenMapper.findValidToken(token);
        if (downloadToken == null) {
            throw new BusinessException("无效的下载令牌或令牌已过期");
        }

        // 标记令牌为已使用
        downloadTokenMapper.markAsUsed(downloadToken.getId());

        // 增加项目下载次数
        projectMapper.incrementDownloadCount(downloadToken.getProjectId());

        // 记录下载
        DownloadRecord downloadRecord = new DownloadRecord();
        downloadRecord.setUserId(downloadToken.getUserId());
        downloadRecord.setProjectId(downloadToken.getProjectId());
        downloadRecord.setIpAddress(ipAddress);
        downloadRecord.setIsSuccessful(true);
        downloadRecordMapper.insert(downloadRecord);

        // 获取项目文件路径
        Project project = projectMapper.findById(downloadToken.getProjectId());

        // 优先返回Gitee下载链接，如果有的话
        if (project.getGiteeDownloadUrl() != null && !project.getGiteeDownloadUrl().isEmpty()) {
            return project.getGiteeDownloadUrl();
        }

        return project.getFilePath();
    }

    /**
     * 计算项目总数
     */
    public int countPublishedProjects() {
        return projectMapper.countAllPublished();
    }

    /**
     * 计算用户项目总数
     */
    public int countUserProjects(Long userId) {
        return projectMapper.countByCreatorId(userId);
    }

    /**
     * 上传文件到Gitee仓库
     */
    public String uploadFileToGitee(byte[] fileContent, String fileName, String repoName) {
        try {
            // Base64编码文件内容
            String content = Base64.getEncoder().encodeToString(fileContent);

            // 构建API请求
            Map<String, Object> requestParams = new HashMap<>();
            requestParams.put("access_token", giteeAccessToken);
            requestParams.put("content", content);
            requestParams.put("message", "上传文件: " + fileName);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestParams, headers);

            // 调用Gitee API上传文件
            String apiUrl = "https://gitee.com/api/v5/repos/" + giteeOwner + "/" + repoName +
                    "/contents/" + fileName;

            ResponseEntity<Map> response = restTemplate.postForEntity(apiUrl, requestEntity, Map.class);

            if (response.getStatusCode().is2xxSuccessful()) {
                // 返回原始文件下载链接
                return "https://gitee.com/" + giteeOwner + "/" + repoName + "/raw/master/" + fileName;
            } else {
                throw new BusinessException("上传文件到Gitee失败: " + response.getBody());
            }
        } catch (Exception e) {
            throw new BusinessException("上传文件到Gitee异常: " + e.getMessage());
        }
    }

    /**
     * 获取所有项目分类
     */
    public List<Map<String, Object>> getAllCategories() {
        try {
            List<ProjectCategory> categories = categoryMapper.findAll();

            // 如果没有分类数据，返回默认分类
            if (categories == null || categories.isEmpty()) {
                List<Map<String, Object>> defaultCategories = new ArrayList<>();

                Map<String, Object> web = new HashMap<>();
                web.put("id", 1L);
                web.put("name", "Web应用");
                web.put("description", "基于Web的应用程序");

                Map<String, Object> mobile = new HashMap<>();
                mobile.put("id", 2L);
                mobile.put("name", "移动应用");
                mobile.put("description", "手机、平板等移动设备上的应用程序");

                Map<String, Object> desktop = new HashMap<>();
                desktop.put("id", 3L);
                desktop.put("name", "桌面应用");
                desktop.put("description", "PC桌面上运行的应用程序");

                defaultCategories.add(web);
                defaultCategories.add(mobile);
                defaultCategories.add(desktop);

                return defaultCategories;
            }

            List<Map<String, Object>> result = new ArrayList<>();
            for (ProjectCategory category : categories) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", category.getId());
                map.put("name", category.getName());
                map.put("description", category.getDescription());
                result.add(map);
            }

            return result;
        } catch (Exception e) {
            // 发生异常时返回默认分类
            List<Map<String, Object>> defaultCategories = new ArrayList<>();

            Map<String, Object> web = new HashMap<>();
            web.put("id", 1L);
            web.put("name", "Web应用");
            web.put("description", "基于Web的应用程序");

            Map<String, Object> mobile = new HashMap<>();
            mobile.put("id", 2L);
            mobile.put("name", "移动应用");
            mobile.put("description", "手机、平板等移动设备上的应用程序");

            Map<String, Object> desktop = new HashMap<>();
            desktop.put("id", 3L);
            desktop.put("name", "桌面应用");
            desktop.put("description", "PC桌面上运行的应用程序");

            defaultCategories.add(web);
            defaultCategories.add(mobile);
            defaultCategories.add(desktop);

            return defaultCategories;
        }
    }

    /**
     * 获取所有项目标签
     */
    public List<Map<String, Object>> getAllTags() {
        try {
            // 尝试获取所有唯一标签
            List<String> uniqueTags = tagMapper.findAllUniqueTags();

            // 如果没有标签数据，返回默认标签
            if (uniqueTags == null || uniqueTags.isEmpty()) {
                return getDefaultTags();
            }

            List<Map<String, Object>> result = new ArrayList<>();
            int id = 1;
            for (String tagName : uniqueTags) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", id++);
                map.put("name", tagName);
                result.add(map);
            }

            return result;
        } catch (Exception e) {
            // 发生异常时返回默认标签
            return getDefaultTags();
        }
    }

    /**
     * 获取默认标签
     */
    private List<Map<String, Object>> getDefaultTags() {
        List<Map<String, Object>> defaultTags = new ArrayList<>();

        String[] tagNames = {"Java", "Python", "JavaScript", "Vue", "React", "Spring Boot",
                "Android", "iOS", "HTML/CSS", "数据库", "工具", "游戏"};

        for (int i = 0; i < tagNames.length; i++) {
            Map<String, Object> tag = new HashMap<>();
            tag.put("id", i + 1);
            tag.put("name", tagNames[i]);
            defaultTags.add(tag);
        }

        return defaultTags;
    }

    /**
     * 更新项目实体，添加Gitee仓库相关字段
     */
    public void addGiteeFields(Project project, String giteeRepoName, String giteeRepoUrl, String giteeDownloadUrl) {
        project.setGiteeRepoName(giteeRepoName);
        project.setGiteeRepoUrl(giteeRepoUrl);
        project.setGiteeDownloadUrl(giteeDownloadUrl);

        // 如果项目使用Gitee托管，将Gitee下载URL作为文件路径
        if (giteeDownloadUrl != null && !giteeDownloadUrl.isEmpty()) {
            project.setFilePath(giteeDownloadUrl);
        }

        projectMapper.update(project);
    }
}